package com.twotiger.and.activity.account;

import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.HomeActivity;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.account.capitalflow.CapitalFlowPage;
import com.twotiger.and.activity.account.cash.CashPage;
import com.twotiger.and.activity.account.recharge.RechargePage;
import com.twotiger.and.activity.base.BaseFragment;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.current.CurrentHost;
import com.twotiger.and.activity.others.MorePage;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.adapter.AccountOptionsAdapter;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.CapitalCompare;
import com.twotiger.and.bean.CapitalCompareItem;
import com.twotiger.and.bean.CashBank;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.CurrentAccount;
import com.twotiger.and.bean.RechargeBank;
import com.twotiger.and.bean.User;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.bean.WithdrawBank;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PreferencesUtils;
import com.twotiger.and.util.TimeUtils;
import com.twotiger.and.view.UnSlideGridView;
import com.twotiger.and.view.WaveView;
import com.view.pulltorefresh.PullToRefreshBase;
import com.view.pulltorefresh.PullToRefreshScrollView;

/**
 * 
 * @Description: 
 * 我的账户 
 * @Author gao
 * @Date 2015年8月12日 下午1:38:31
 */
public class AccountPage extends BaseFragment implements OnClickListener {

    private PullToRefreshScrollView account_sc;
    private final static int OPEN_PAYMENT_SUCESS = 0;
    private final static int OPEN_PAYMENT_FAIL = 1;
    private final static int GET_ASSERT_SUCCES = 2;
    private final static int GET_ASSERT_FAIL = 3;
    public final static int GET_CUNBANK_SUCCES = 4;
    private final static int GET_CUNBANK_FAIL = 5;
    private final static int GET_USERINFO_SSUCESS = 6;
    private final static int GET_USERINFO_FAIL = 7;
    private final static int GET_QUBANK_SUCCES = 8;
    private final static int GET_QUBANK_FAIL = 9;
    private final static int GET_CHARTCOMPARE_SUCCES = 10;
    private final static int GET_CHARTCOMPARE_FAIL = 11;

    public final static int GETCURRENTPROJECTXACOUNTSUCCES = 14;
    public final static int GETCURRENTPROJECTXACOUNTFAIL = 15;

    private BaseHandler handler;
    private HashMap<String, String> parms;
    private HomeActivity activity;
    private UnSlideGridView option_grid;
    private TextView todayincome_value, tv_total_inverst;
    private TextView available_balance;
    private TextView all_balance;
    private static String TAG_refresh = "AccountPage_time";
    private RelativeLayout day_inverst_layout, total_inverst_layout;
    private RelativeLayout all_layout;
    private View can_use_layout;
    private ScrollView account_sc_notlogin;
    private TextView tv_name1, tv_name2, tv_name3, tv_name4;
    private WaveView wv_tiger, wv_currency, wv_bank_dingqi, wv_bank_huoqi;
    private Button btn_register, btn_login;

    protected View loadViewLayout(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.account_layout, null);
        return view;
    }

    private HomeActivity getContext() {
        return (HomeActivity) getActivity();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.title_left_bt:
            ConstantDataUnit ptgg = mactivity.getConstantDataByKey(Constants.dz_ptgg);
            if (ptgg != null) {
                Intent in_gg = new Intent(getActivity(), WebViewPage.class);
                in_gg.putExtra("title", "平台公告");
                in_gg.putExtra("url", ptgg.getVal());
                startnewActivity(in_gg, R.anim.push_left_in, R.anim.push_left_out, false);
            }
            break;
        case R.id.day_inverst_layout: //昨日收益
            Intent in1 = new Intent(getActivity(), TotalAssetPage.class).putExtra(
                TotalAssetPage.SHOWWHICH, TotalAssetPage.SHOWWHICH_YESTERDAY);
            startnewActivity(in1, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.total_inverst_layout: //累计赚取
            Intent in2 = new Intent(getActivity(), TotalAssetPage.class).putExtra(
                TotalAssetPage.SHOWWHICH, TotalAssetPage.SHOWWHICH_EARN);
            startnewActivity(in2, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.can_use_layout: //可用余额
            Intent in3 = new Intent(getActivity(), CapitalFlowPage.class);
            startnewActivity(in3, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.all_layout://总资产
            Intent in4 = new Intent(getActivity(), TotalAssetPage.class).putExtra(
                TotalAssetPage.SHOWWHICH, TotalAssetPage.SHOWWHICH_ASSET);
            startnewActivity(in4, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.btn_register:
            //            Intent intent1 = new Intent(getActivity(), RegisterPage.class);
            //            startnewActivity(intent1, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
            Intent intent1 = new Intent(getActivity(), LoginPage.class);
            intent1.putExtra("witchLayout", "regist");
            startnewActivity(intent1, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
            break;
        case R.id.btn_login:
            Intent intent2 = new Intent(getActivity(), LoginPage.class);
            startnewActivity(intent2, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
            break;
        default:
            break;

        }
    }

    /**
     * 未登录状态 资金收益对比接口
     */
    private void getCapitalCompare() {
        parms.clear();
        getContext().getDate(parms, Constants.CHARTCOMPAREQUERY, handler, GET_CHARTCOMPARE_SUCCES,
            GET_CHARTCOMPARE_FAIL, false, true, false);
    }

    /**
     * 获取支付详情
     */
    public void getpayment() {
        parms.clear();
        parms.put("token", getContext().getToken());
        getContext().getDate(parms, Constants.REGISTHF, handler, OPEN_PAYMENT_SUCESS,
            OPEN_PAYMENT_FAIL, true, true, false);
    }

    /**
     * 获取用户信息
     */
    private void getuserinfo() {
        parms.clear();
        parms.put("token", activity.getToken());
        getContext().getDate(parms, Constants.USERINFOQUERY, handler, GET_USERINFO_SSUCESS,
            GET_USERINFO_FAIL, false, false, false);
    }

    /**O
     * 获取用户资产
     */
    private void getuserAsset() {
        parms.clear();
        parms.put("token", getContext().getToken());
        getContext().getDate(parms, Constants.ASSETQUERY, handler, GET_ASSERT_SUCCES,
            GET_ASSERT_FAIL, false, true, false);
    }

    @Override
    protected void setListener() {
        handler = new BaseHandler(activity) {
            private UserAsset userAsset;

            @Override
            public void handleMessage(Message msg) {
                Intent intent = new Intent();
                switch (msg.what) {
                case OPEN_PAYMENT_SUCESS:
                    Basebean result_open = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_open.isOk()) {
                        BroswerUrl responseinfo = JSON.parseObject(result_open.data,
                            BroswerUrl.class);
                        intent.setClass(getContext(), WebViewPage.class)
                            .putExtra("title", "汇付天下托管账号").putExtra("url", responseinfo.getUrl())
                            .putExtra("BUSINESS_TYPE", WebViewPage.TYPE_PAYMENT_REGIST);
                        startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                    break;
                case GET_ASSERT_SUCCES:
                    Basebean result_2 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_2.isOk()) {
                        account_sc.getLoadingLayoutProxy().setLastUpdatedLabel(
                            "最后更新：今天 " + TimeUtils.getFormatDate(" HH:mm"));
                        userAsset = JSONObject.parseObject(result_2.data, UserAsset.class);
                        mactivity.application.setUserAsset(userAsset);
                        todayincome_value.setText(ArithUtils.coverMoneyComma(userAsset.yesDayInt
                                                                             + ""));
                        tv_total_inverst.setText(ArithUtils
                            .coverMoneyComma(userAsset.totalInt + ""));
                        available_balance.setText(ArithUtils.coverMoneyComma(userAsset.avaliable
                                                                             + ""));
                        all_balance.setText(ArithUtils.coverMoneyComma(userAsset.total + ""));

                        option_grid.setAdapter(new AccountOptionsAdapter(getActivity(), userAsset,
                            handler, activity.hasOpenThirdAct(), 0));
                    }
                    account_sc.onRefreshComplete();
                    break;
                case GET_ASSERT_FAIL:
                    account_sc.onRefreshComplete();
                    break;
                case GET_QUBANK_SUCCES:
                    Basebean result_q = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_q.isOk()) {
                        WithdrawBank mWithdrawBank = JSON.parseObject(result_q.data,
                            WithdrawBank.class);
                        activity.application.setCashBanks(JSON.parseArray(
                            mWithdrawBank.getBankList(), CashBank.class));
                        intent.setClass(activity, CashPage.class);
                        if (userAsset != null) {
                            intent.putExtra("GETCASH", userAsset.avaliable);
                        }
                        intent.putExtra("WITHDRAWBANK", mWithdrawBank);
                        startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    } else {
                        showToast(result_q.codeDesc);
                    }

                    //                    UserBanklist userbanklist = JSON.parseObject((String) msg.obj,
                    //                        UserBanklist.class);
                    //                    if (userbanklist.isOk()) {
                    //                        if (userbanklist.isOk()) {
                    //                            mactivity.application.setUserBanks(JSON.parseArray(
                    //                                userbanklist.getBankList(), BanklistItem.class));
                    //                        }
                    //                        //跳转到提现界面
                    //                        intent.setClass(activity, CashPage.class);
                    //                        intent.putExtra("TIXIAN_JSON", userbanklist.getBankList());
                    //                        if (userAsset != null) {
                    //                            intent.putExtra("GETCASH", userAsset.avaliable);
                    //                        }
                    //                        startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    //                    }
                    break;
                case GET_CHARTCOMPARE_SUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        CapitalCompare capitalCompare = JSON.parseObject(result.data,
                            CapitalCompare.class);
                        List<CapitalCompareItem> capitalCompareItem = JSON.parseArray(
                            capitalCompare.getList(), CapitalCompareItem.class);
                        fillNotLoginData(capitalCompareItem);
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case GET_CHARTCOMPARE_FAIL:
                case OPEN_PAYMENT_FAIL:
                case GET_USERINFO_FAIL:
                case GET_QUBANK_FAIL:
                case GET_CUNBANK_FAIL:
                    showToast("网络不佳，请重试");
                    break;
                case GET_USERINFO_SSUCESS:
                    Basebean result_1 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_1.isOk()) {
                        User user = JSON.parseObject(result_1.data, User.class);
                        activity.application.setUser(user);
                    }
                    break;
                case GET_CUNBANK_SUCCES:
                    Basebean result_b = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_b.isOk()) {
                        RechargeBank mRechargeBank = JSON.parseObject(result_b.data,
                            RechargeBank.class);
                        intent.setClass(activity, RechargePage.class);
                        if (userAsset != null) {
                            intent.putExtra("CHARGE", userAsset.avaliable);
                        }
                        intent.putExtra("RECHARGEBANK", mRechargeBank);
                        startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    } else {
                        showToast(result_b.codeDesc);
                    }
                    //                    UserBanklist cunbanklist = JSON.parseObject((String) msg.obj,
                    //                        UserBanklist.class);
                    //                    if (cunbanklist.isOk()) {
                    //                        //跳转到充值
                    //                    }

                    break;
                case GETCURRENTPROJECTXACOUNTSUCCES:
                    Basebean result_c = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_c.isOk()) {
                        CurrentAccount mCurrentAccount = JSON.parseObject(result_c.data,
                            CurrentAccount.class);
                        intent.setClass(activity, CurrentHost.class);
                        intent.putExtra("CURRENTACCOUNT", mCurrentAccount);
                        startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    } else {
                        showToast(result_c.codeDesc);
                    }
                    break;
                case GETCURRENTPROJECTXACOUNTFAIL:
                    showToast("网络不佳，请重试");
                    break;

                default:
                    break;
                }
                super.handleMessage(msg);
            }

        };
        account_sc.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getuserAsset();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            }
        });
        total_inverst_layout.setOnClickListener(this);
        day_inverst_layout.setOnClickListener(this);
        can_use_layout.setOnClickListener(this);
        all_layout.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        btn_login.setOnClickListener(this);
    }

    protected void fillNotLoginData(List<CapitalCompareItem> capitalCompareItem) {
        tv_name1.setText(capitalCompareItem.get(0).getName());
        tv_name2.setText(capitalCompareItem.get(1).getName());
        tv_name3.setText(capitalCompareItem.get(2).getName());
        tv_name4.setText(capitalCompareItem.get(3).getName());

        Double profit_tiger = stringToDouble(capitalCompareItem.get(0).getVal());
        Double profit_currency = stringToDouble(capitalCompareItem.get(1).getVal());
        Double profit_bank_dingqi = stringToDouble(capitalCompareItem.get(2).getVal());
        Double profit_bank_huoqi = stringToDouble(capitalCompareItem.get(3).getVal());

        wv_tiger.setBlankHeight((profit_tiger - profit_tiger) / profit_tiger, profit_tiger);
        wv_currency
            .setBlankHeight((profit_tiger - profit_currency) / profit_tiger, profit_currency);
        wv_bank_dingqi.setBlankHeight((profit_tiger - profit_bank_dingqi) / profit_tiger,
            profit_bank_dingqi);
        wv_bank_huoqi.setBlankHeight((profit_tiger - profit_bank_huoqi) / profit_tiger,
            profit_bank_huoqi);

    }

    private Double stringToDouble(String val) {
        Double profit = 0.0;
        if (val == null) {
            return 0.0;
        } else {
            profit = Double.parseDouble(val.substring(0, val.length() - 1));
        }
        return profit;
    }

    @Override
    protected void processLogic() {
        parms = getContext().getParm();
        account_sc.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        //先将界面在数据之前渲染出来
        option_grid.setAdapter(new AccountOptionsAdapter(getActivity(), null, handler, activity
            .hasOpenThirdAct(), 0));

        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void initData() {
        if (getContext().isLogin()) {
            getuserAsset();
            getuserinfo();
        } else {
            getCapitalCompare();
        }
    }

    @Override
    protected void findViewById(View view) {
        activity = (HomeActivity) getActivity();

        account_sc = (PullToRefreshScrollView) view.findViewById(R.id.account_sc); //登录状态的布局
        account_sc_notlogin = (ScrollView) view.findViewById(R.id.account_sc_notlogin); //未登录状态布局

        can_use_layout = view.findViewById(R.id.can_use_layout);
        option_grid = (UnSlideGridView) view.findViewById(R.id.option_grid);
        day_inverst_layout = (RelativeLayout) view.findViewById(R.id.day_inverst_layout);
        total_inverst_layout = (RelativeLayout) view.findViewById(R.id.total_inverst_layout);
        all_layout = (RelativeLayout) view.findViewById(R.id.all_layout);
        todayincome_value = (TextView) view.findViewById(R.id.todayincome_value);
        tv_total_inverst = (TextView) view.findViewById(R.id.tv_total_inverst);
        available_balance = (TextView) view.findViewById(R.id.available_balance);
        all_balance = (TextView) view.findViewById(R.id.all_balance);

        View fl_inner = account_sc.findViewById(R.id.fl_inner);
        fl_inner.setBackgroundColor(getResources().getColor(app.twotiger.p2p.R.color.bg_1));

        //未登录状态 各id
        tv_name1 = (TextView) view.findViewById(R.id.tv_name1);
        tv_name2 = (TextView) view.findViewById(R.id.tv_name2);
        tv_name3 = (TextView) view.findViewById(R.id.tv_name3);
        tv_name4 = (TextView) view.findViewById(R.id.tv_name4);
        wv_tiger = (WaveView) view.findViewById(R.id.wv_tiger);
        wv_currency = (WaveView) view.findViewById(R.id.wv_currency);
        wv_bank_dingqi = (WaveView) view.findViewById(R.id.wv_bank_dingqi);
        wv_bank_huoqi = (WaveView) view.findViewById(R.id.wv_bank_huoqi);
        btn_register = (Button) view.findViewById(R.id.btn_register);
        btn_login = (Button) view.findViewById(R.id.btn_login);
        //判断是否登录状态，显示不同布局
        if (getContext().isLogin()) {
            account_sc.setVisibility(View.VISIBLE);
            account_sc_notlogin.setVisibility(View.GONE);
        } else {
            account_sc.setVisibility(View.GONE);
            account_sc_notlogin.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean isNeedLogin() {
        return false;
    }

    @Override
    public String getTitle() {
        //判断是否登录状态
        if (getContext().isLogin()) {
            return "我的账户";
        } else {
            return "收益对比";
        }
    }

    @Override
    public void rebuildTitleStyle() {
        subTitle.setBgResource(R.drawable.bg_account_title).setColor(Color.WHITE)
            .setTitle(getTitle()).hideBottomLine();
        mactivity.tintManager.setTintResource(R.drawable.bg_account_statusbar);
        mactivity.setLayoutPadding(false);

        subTitle.title_right_bt.setVisibility(View.VISIBLE);
        subTitle.title_right_bt.setImageResource(R.drawable.to_others);

        subTitle.title_left_bt.setVisibility(View.VISIBLE);
        subTitle.title_left_bt.setImageResource(R.drawable.to_notice);
        subTitle.title_left_bt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ConstantDataUnit ptgg = mactivity.getConstantDataByKey(Constants.dz_ptgg);
                if (ptgg != null) {
                    Intent in_gg = new Intent(getActivity(), WebViewPage.class);
                    in_gg.putExtra("title", "平台公告");
                    in_gg.putExtra("url", ptgg.getVal());
                    startnewActivity(in_gg, R.anim.push_left_in, R.anim.push_left_out, false);
                }
            }
        });
    }

    @Override
    public void clickRightBtnIml() {
        Intent intent = new Intent(mactivity, MorePage.class);
        startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            option_grid.setFocusable(false);
            if (account_sc != null) {
                account_sc.scrollToTop();
            }
        } else {
            option_grid.setFocusable(false);
            if (account_sc != null) {
                account_sc.scrollToTop();
            }
            //判断是否登录状态，显示不同布局
            if (getContext().isLogin()) {
                getuserAsset();
                getuserinfo();
                account_sc.setVisibility(View.VISIBLE);
                account_sc_notlogin.setVisibility(View.GONE);
            } else {
                getCapitalCompare();
                account_sc.setVisibility(View.GONE);
                account_sc_notlogin.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void reLoadData() {

    }

}
